<?php

function village_activity_list_page()
{
    @$output = drupal_render(drupal_get_form('village_activity_list_form'));
    return $output;
}

function village_activity_list_form($form, &$form_state)
{
    if (!empty($_GET['addr_id'])) {
        $form_state['addr_id'] = $_GET['addr_id'];
    }
    if (empty($form_state['addr_id'])) {
        $form['address_fuzzy'] = _insert_address_autocomplete($form, $form_state);
        $form['address'] = _insert_address_selection_form($form, $form_state, 'address', 5, FALSE, _get_address_id($form_state), '', '', TRUE);
    }else{
        $form['#addr_id'] = $form_state['addr_id'];
        $addr_red = get_all_addrname($form['#addr_id']);
        $province = $addr_red[0]->province?$addr_red[0]->province:"";
        $city = $addr_red[0]->city? '  '.$addr_red[0]->city:"";
        $county = $addr_red[0]->county? '  '.$addr_red[0]->county:"";
        $town = $addr_red[0]->town? '  '.$addr_red[0]->town:"";
        $village = $addr_red[0]->village? '  '.$addr_red[0]->village:"";
        $form['#addr'] =$province.$city.$county.$town.$village;
    }
//    $form['distributor'] = get_all_distributors();
    $form['address_distributor_markup']['#markup'] = '<div class="address-distributor-search">';
    $form['address_distributor'] = _insert_distributor1_selection_form($form, $form_state, 'address_distributor');
    $form['address_distributor_markup_close']['#markup'] = '</div>';
    $init_year = !empty($form_state['values']['year']) ? $form_state['values']['year'] : "";
    $init_month = !empty($form_state['values']['month']) ? $form_state['values']['month'] : "";
    _insert_date_selection_form($form, $form_state, 5, $init_year, $init_month);
    $form['title_fuzzy'] = array(
        '#type' => 'textfield',
        '#title' => '标题',
        '#default_value' => !empty($form_state['values']['title_fuzzy']) ? $form_state['values']['title_fuzzy'] : "",
        '#maxlength' => 20,
    );
    $form['content_fuzzy'] = array(
        '#type' => 'textfield',
        '#title' => '内容',
        '#default_value' => !empty($form_state['values']['content_fuzzy']) ? $form_state['values']['content_fuzzy'] : "",
        '#maxlength' => 20,
    );
    $form['attendees_fuzzy'] = array(
        '#type' => 'textfield',
        '#title' => '参与人',
        '#default_value' => !empty($form_state['values']['attendees_fuzzy']) ? $form_state['values']['attendees_fuzzy'] : "",
        '#maxlength' => 20,
    );
    if(!empty($_GET['special_activities'])){
        $special_activities_title = get_special_activities_title($_GET['special_activities']);
    }
    $form['special_activities'] = array(
        '#type' => 'textfield',
        '#title' => '专项活动',
        '#size' => 32,
        '#maxlength' => 50,
        '#id'=>'special_activities_textfield',
        '#default_value' => $special_activities_title,
    );
    $table['#markup'] = data_list_view_page($form, $form_state);
    ajax_submit_form($form, $form_state, $table, '');
    return $form;
}

function village_activity_list_form_validate($form, &$form_state)
{
}

function data_list_view_page(&$form = '', &$form_state = '')
{
    global $user;
    $output = '';
    //表头
    $header = array(
        array('data' => '选择', 'class' => ['essential no']),
        isset($form_state['addr_id']) && !empty($form_state['addr_id']) ? "" :
        array('data' => '地址', 'class' => ['essential province city county']),
        array('data' => '经销商', 'class' => ['essential store-name']),
        array('data' => '标题', 'class' => ['essential more']),
        array('data' => '活动内容', 'class' => ['essential more']),
        array('data' => '参与人员', 'class' => ['essential more']),
        array('data' => '活动日期', 'class' => ['essential more'], 'field' => 'date'),
        array('data' => '提交者', 'class' => ['essential more']),
        array('data' => '操作', 'class' => ['essential more']),
    );

    $query = db_select('addr', 'A')->extend('PagerDefault')->extend('TableSort');
    $query->join('village_activity', 'V', 'A.addr_id=V.addr_id');
    $query->join('distributor', 'D', 'D.distributor_id=V.distributor_id');
    //地址级别查询
    _address_search_conditon($query,$form_state);
    $datestr = '';
    if (!empty($form_state['values']['year'])) {//查询条件
        if ($form_state['values']['year']) {
            $datestr .= $form_state['values']['year'] . '-';
        }
    }
    if (!empty($form_state['values']['month'])) {//查询条件
        if ($month = $form_state['values']['month']) {
            if ($month < 10)
                $datestr .= '0' . $form_state['values']['month'];
            else
                $datestr .= $form_state['values']['month'];
        }
    }
    if ($datestr) {
        $query->condition('V.date', db_like($datestr) . '%', 'LIKE');
    }
    if (!empty($form_state['values']['title_fuzzy'])) {//查询条件
        $query->condition('V.title', '%' . db_like($form_state['values']['title_fuzzy']) . '%', 'LIKE');
    }
    if (!empty($form_state['values']['content_fuzzy'])) {//查询条件
        $query->condition('V.body', '%' . db_like($form_state['values']['content_fuzzy']) . '%', 'LIKE');
    }
    if (!empty($form_state['values']['attendees_fuzzy'])) {//查询条件
        $query->condition('V.attendee', '%' . db_like($form_state['values']['attendees_fuzzy']) . '%', 'LIKE');
    }
    if (!empty($form_state['values']['distributor'])) {//查询条件
//        $query->condition('V.distributor_id', $form_state['values']['distributor'], '=');
        $query->condition('D.distributor_name', '%'.db_like($form_state['values']['distributor']).'%', 'LIKE');
    }
    if(!user_access('view all village_activity') && user_access('view own village_activity')){
        $query->condition('V.author_uid',$user->uid,'=');
    }

//专项活动
    if(!empty($form_state['values']['special_activities'])){
        $special_activities_id = get_id_from_string_field('special_activities','special_activities_id','title',$form_state['values']['special_activities'],false);
        if(!empty($special_activities_id)){
            $query->condition('V.special_activities_id',$special_activities_id, '=');
        }else{
            $query->condition('V.special_activities_id',0, '=');
        }
    }
    if(!empty($_GET['special_activities'])){
        $query->condition('V.special_activities_id',$_GET['special_activities'], '=');
    }
    if (isset($form_state['addr_id']) && !empty($form_state['addr_id'])) {
        $query->condition('V.addr_id', $form_state['addr_id']);

    }
    $query->fields('V');
    $query->leftJoin('addr', 'A1', 'A.province_id=A1.addr_id');
    $query->leftJoin('addr', 'A2', 'A.city_id=A2.addr_id');
    $query->leftJoin('addr', 'A3', 'A.county_id=A3.addr_id');
    $query->leftJoin('addr', 'A4', 'A.town_id=A4.addr_id');
    $query->leftJoin('employee', 'E', 'E.employee_id=V.author_uid');
    //$query->leftJoin('address', 'town', 'addr.town_id=town.id');
    $query->addField('A', 'name', 'village');
    $query->addField('A1', 'name', 'province');
    $query->addField('A2', 'name', 'city');
    $query->addField('A3', 'name', 'county');
    $query->addField('A4', 'name', 'town');
    $query->addField('D', 'distributor_name');
    $query->addField('E', 'employee_name');
    //$query->addField('town', 'name', 'town');

    $statQuery = $query->cloneQuery();
    $statQuery->addExpression('count(*)','count');
    $statInfo = $statQuery->execute()->fetchObject();
    $form["#stat"]['#count'] = $statInfo->count;

    if(empty($form_state['values']) || empty($form_state['values']['order'])) {
        $query->orderBy('V.timestamp', 'DESC');
    }
    $query->limit(variable_get("list_page_item_number", 5));
    $village_activityInfo = $query->orderByHeader($header)->execute();
    $rows = array();
    //表内容
    $n = 1;
    foreach ($village_activityInfo as $row) {
        $city = $row->city ? ' ' . $row->city : '';
        $county = $row->county ? ' ' . $row->county : '';
        $town = $row->town ? ' ' . $row->town : '';
        $village = $row->village ? ' ' . $row->village : '';
        if (nonghua_user_access('village_activity', 'delete', $row->village_activity_id, $row->author_uid, 0)) {
            $disabled = ' class="listViewTableCheck" ';
        } else{
            $disabled = ' disabled="true" ';
        }
        $rows[] = array(
            array('data' => "<input type='checkbox''.$disabled.' value ='" . $row->village_activity_id . "' name='" . $row->village_activity_id . "'/>" . $n++, 'class' => 'integrant essential no'),
            isset($form_state['addr_id']) && !empty($form_state['addr_id']) ? "" :
            array('data' => $row->province . $city . $county . $town.$village, 'class' => ['integrant haveTobr essential province city county']),
//                array('data' =>'<a href="'.base_path().'village/activity/edit/' . $row->village_activity_id . '">'. $row->province . $city . $county . $town . $village_activity."</a>", 'class' => ['integrant haveTobr essential province city county']),
            array('data' => '<a target="_top" href="'.base_path().'distributor/edit/' . $row->distributor_id . '?distributor_id='.$row->distributor_id.'">'.$row->distributor_name.'</a', 'class' => ['integrant essential store-name']),
            array('data' => $row->title, 'class' => ['integrant goRight essential phone']),
            array('data' => $row->body, 'class' => ['integrant goRight essential phone']),
            array('data' => $row->attendee, 'class' => ['integrant goRight essential phone']),
            array('data' => $row->date, 'class' => ['integrant goRight essential phone']),
            array('data' => $row->employee_name, 'class' => ['integrant goRight essential phone']),
            isset( $form_state['addr_id']) && !empty( $form_state['addr_id'])?
            array('data' => '<a href="' . base_path() . 'village/activity/edit/'.$row->village_activity_id . '?addr_id='. $form_state['addr_id'].'"
            data-toggle="modal" target="_self"><img width="20px" height="20px" src="' . base_path() . 'sites/all/themes/tweme/images/images/cz.png"/></a>', 'class' => 'essential more'):
            array('data' => '<a href="' . base_path() . 'village/activity/edit/' . $row->village_activity_id . '"  data-toggle="modal" ><img width="20px" height="20px" src="' . base_path() . 'sites/all/themes/tweme/images/images/cz.png"/></a>', 'class' => 'essential more'),
        );
    }

    $output .= theme('table', array('header' => $header, 'rows' => $rows, 'empty' => t('没有记录'), 'attributes' => array('class' => array('table table-bordered table-striped table-hover enhanced')))); //表格
    /*	 * *按钮** */
    if (sizeof($rows) > 0 && (user_access('delete own village_activity') ||  user_access('delete all village_activity'))) {
        $output .= '<a href="javascript:void(0)" id="listViewTableSelectAll" data-toggle="modal" class="btn btn-mini">全选</a>';
        $output .= '<a href="javascript:void(0)" id="listViewTableDeleteSelected" data-toggle="modal" class="btn btn-mini">删除所选</a>';
    }
    if(!empty($form_state['values']['village'])){
        $new_addr_id = $form_state['values']['village'];
        $str = 'village=';
    }elseif(!empty($form_state['values']['town'])){
        $new_addr_id = $form_state['values']['town'];
        $str = 'town=';
    }elseif(!empty($form_state['values']['county'])){
        $new_addr_id = $form_state['values']['county'];
        $str = 'county=';
    }elseif(!empty($form_state['values']['city'])){
        $new_addr_id = $form_state['values']['city'];
        $str = 'city=';
    }elseif(!empty($form_state['values']['province'])){
        $new_addr_id = $form_state['values']['province'];
        $str = 'province=';
    }
    $str .= $new_addr_id;
    $output .= '<a href="'.base_path().'village_activity/export?'.$str.'&address_fuzzy='.$form_state['values']['address_fuzzy'].'&distributor='.$form_state['values']['distributor'].'&year='.$form_state['values']['year'].'&month='.$form_state['values']['month'].'&special_activities='.$form_state['values']['special_activities'].'&title_fuzzy='.$form_state['values']['title_fuzzy'].'&content_fuzzy='.$form_state['values']['content_fuzzy'].'&attendees_fuzzy='.$form_state['values']['attendees_fuzzy'].'" data-toggle="modal" class="btn btn-mini">导出</a>';
    $output .= theme('pager');
    return $output;
}

function village_activity_delete()
{
    ajax_table_delete('village_activity', 'village_activity_id');
}

function village_activity_export($form,&$form_state){
    $letter = array('A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z');
    $tableheader = array('地址','经销商','标题','活动内容','参与人员','活动日期','提交者');
    $data = get_village_activity_data($form, $form_state);
    nonghua_php_excel($letter,$tableheader,$data,'村落活动信息数据');
}

function get_village_activity_data($form = '', &$form_state = ''){
    global $user;
    $user_info = _get_user_info($user->uid);
    $query = db_select('addr', 'A');
    $query->join('village_activity', 'V', 'A.addr_id=V.addr_id');
    $query->join('distributor', 'D', 'D.distributor_id=V.distributor_id');
    //地址级别查询
    if (!empty($_GET['village'])) {//村落级
        $query->condition('A.village_id', $_GET['village'], '=');
    } else if (!empty($_GET['town'])) {//乡镇级
        $query->condition('A.town_id', $_GET['town'], '=');
    } elseif (!empty($_GET['county'])) {//县级
        $query->condition('A.county_id', $_GET['county'], '=');
    } elseif (!empty($_GET['city'])) {//市级
        $query->condition('A.city_id', $_GET['city'], '=');
    } elseif (!empty($_GET['province'])) {//省级
        $query->condition('A.province_id', $_GET['province'], '=');
    }
    if (!empty($_GET['address_fuzzy'])) {
        $or = db_or()->condition('A.name', '%' . db_like($_GET['address_fuzzy']) . '%', 'like');
        $query->condition($or);
    }
    $datestr = '';
    if (!empty($_GET['year'])) {//查询条件
        if ($_GET['year']) {
            $datestr .= $_GET['year'] . '-';
        }
    }
    if (!empty($_GET['month'])) {//查询条件
        if ($month = $_GET['month']) {
            if ($month < 10)
                $datestr .= '0' . $_GET['month'];
            else
                $datestr .= $_GET['month'];
        }
    }
    if ($datestr) {
        $query->condition('V.date', db_like($datestr) . '%', 'LIKE');
    }
    if (!empty($_GET['title_fuzzy'])) {//查询条件
        $query->condition('V.title', '%' . db_like($_GET['title_fuzzy']) . '%', 'LIKE');
    }
    if (!empty($_GET['content_fuzzy'])) {//查询条件
        $query->condition('V.body', '%' . db_like($_GET['content_fuzzy']) . '%', 'LIKE');
    }
    if (!empty($_GET['attendees_fuzzy'])) {//查询条件
        $query->condition('V.attendee', '%' . db_like($_GET['attendees_fuzzy']) . '%', 'LIKE');
    }
    if (!empty($_GET['distributor'])) {//查询条件
//        $query->condition('V.distributor_id', $form_state['values']['distributor'], '=');
        $query->condition('D.distributor_name', '%'.db_like($_GET['distributor']).'%', 'LIKE');
    }
    if(!user_access('view all village_activity') && user_access('view own village_activity')){
        $query->condition('V.author_uid',$user->uid,'=');
    }

//专项活动
    if(!empty($_GET['special_activities'])){
        $special_activities_id = get_id_from_string_field('special_activities','special_activities_id','title',$_GET['special_activities'],false);
        if(!empty($special_activities_id)){
            $query->condition('V.special_activities_id',$special_activities_id, '=');
        }else{
            $query->condition('V.special_activities_id',0, '=');
        }
    }
    if (isset($form_state['addr_id']) && !empty($form_state['addr_id'])) {
        $query->condition('V.addr_id', $form_state['addr_id']);

    }
    $query->leftJoin('addr', 'A1', 'A.province_id=A1.addr_id');
    $query->leftJoin('addr', 'A2', 'A.city_id=A2.addr_id');
    $query->leftJoin('addr', 'A3', 'A.county_id=A3.addr_id');
    $query->leftJoin('addr', 'A4', 'A.town_id=A4.addr_id');
    $query->leftJoin('employee', 'E', 'E.employee_id=V.author_uid');
    //$query->leftJoin('address', 'town', 'addr.town_id=town.id');
    $query->addField('A', 'name', 'village');
    $query->addField('A1', 'name', 'province');
    $query->addField('A2', 'name', 'city');
    $query->addField('A3', 'name', 'county');
    $query->addField('A4', 'name', 'town');
    $query->addField('D', 'distributor_name');
    $query->fields('V',array('title','body','attendee','date'));
    $query->addField('E', 'employee_name');
    //$query->addField('town', 'name', 'town');

    $village_activityInfo = $query->execute()->fetchAll();
    foreach($village_activityInfo as $k => $v){
        $village_activityInfo[$k]->province= $v->province.$v->city.$v->county.$v->town.$v->village;
        unset($village_activityInfo[$k]->city);
        unset($village_activityInfo[$k]->county);
        unset($village_activityInfo[$k]->town);
        unset($village_activityInfo[$k]->village);
    }
    return $village_activityInfo;
}